package cn.wsalix.user.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Observable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.admin.BaseUser;
import cn.anlaser.exception.NutException;
import cn.anlaser.service.impl.CommonServiceImpl;
import cn.anlaser.utils.BeanMapper;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.admin.service.UserService;
import cn.wsalix.observable.service.AddressChangeService;
import cn.wsalix.user.entity.Address;
import cn.wsalix.user.form.AddressForm;
import cn.wsalix.user.repository.AddressRepository;
import cn.wsalix.user.service.AddressService;
import cn.wsalix.user.service.UserInfoService;

@Service("addressService")
public class AddressServiceImpl extends
		CommonServiceImpl<AddressForm, AddressRepository, Address> implements
		AddressService {
	@Autowired
	private AddressRepository addressRepository;
	@Autowired
	private UserService userService;
	@Autowired
	private UserInfoService userInfoService;

	@Override
	public String module() {
		return "/user/address";
	}

	@Override
	public AddressRepository getRepository() {
		return addressRepository;
	}

	@Override
	public Address add(AddressForm form) {
		Address obj = BeanMapper.map(form, Address.class);
		obj.setAddress(form.getProvince() + form.getStreet());
		if (form.getUserId() != null && form.getUserId() != 0) {
			// SysUser user = userService.findById(form.getUserId());
			obj.setUserId(form.getUserId());
		} else {
			throw new NutException("添加地址时，未指定用户[userId]");
		}
		if (form.getPretermit() != null && form.getPretermit().equals("on")) {
			form.setSure(true);
		}
		boolean checkExist = checkExist(form);
		if (checkExist) {// 第一条为默认地址
			obj.setSure(true);
		}
		obj.setCreatedDate(new Date());// DateTime.now());
		BaseUser user = userUtils.getUser();
		if (user != null) {
			obj.setCreatedBy(user.getId());
		}
		return super.add(obj);
	}

	@Transactional
	private boolean checkExist(AddressForm form) {
		AddressForm addressForm = new AddressForm();
		addressForm.setUserId(form.getUserId());
		addressForm.setSure(true);
		List<Address> address = findByForm(addressForm);
		if (address == null || address.isEmpty()) {// 第一条为默认地址
			return true;// obj.setSure(true);
		}
		/*
		 * if (form.isSure()) { for (Address obj : address) { obj.setSure(true);
		 * addressRepository.saveAndFlush(obj); } }
		 */
		return false;
	}

	@Override
	public Address edit(AddressForm form) {
		Address obj = addressRepository.findOne(form.getId());
		if (obj == null) {
			// throw Global.getException(existException.getAddressUnExist());
		}
		form.setUserId(obj.getUserId());
		if (form.getPretermit() != null && form.getPretermit().equals("on")) {
			form.setSure(true);
		}
		if (form.getContacts() != null && !form.getContacts().trim().equals("")) {
			obj.setContacts(form.getContacts());
		}
		if (form.getPhone() != null && !form.getPhone().trim().equals("")) {
			obj.setPhone(form.getPhone());
		}
		if (form.getProvince() != null && !form.getProvince().trim().equals("")) {
			obj.setProvince(form.getProvince());
		}
		if (form.getStreet() != null && !form.getStreet().trim().equals("")) {
			obj.setStreet(form.getStreet());
		}
		obj.setAddress(obj.getProvince() + obj.getStreet());
		form.setAddress(obj.getAddress());
		if (form.isSure()) {
			obj.setSure(true);
		}
		obj = edit(obj);
		return obj;
	}

	@Override
	public Class<Address> getEntityClazz() {
		return Address.class;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(AddressForm form) {
		Map<String, SearchFilter> filters = buildFilter(form);
		if (form.getUserId() != null && form.getUserId() != 0) {
			filters.put("userId",
					new SearchFilter("userId", Operator.EQ, form.getUserId()));
		}
		if (form.getPhone() != null && !form.getPhone().equals("")) {
			filters.put("phone",
					new SearchFilter("phone", Operator.EQ, form.getPhone()));
		}
		if (form.isSureQuery()) {
			if (form.isSure()) {
				filters.put("sure", new SearchFilter("sure", Operator.EQ, true));
			} else {
				filters.put("sure",
						new SearchFilter("sure", Operator.EQ, false));
			}
		}
		return filters;
	}

	@Transactional
	@Override
	public void update(Observable o, Object arg) {// 给订单设置收货地址
		if (o instanceof AddressChangeService) {
			AddressChangeService addressChangeService = (AddressChangeService) o;
			if (arg instanceof AddressForm) {
				AddressForm form = (AddressForm) arg;
				Address address = null;
				if (form.getId() == null) {// 新增
					// form.setUserId(user.getId());//不能写死：管理员、客服会新增
					address = add(form);
				} else {// 修改
					// address = findById(form.getId());
					address = edit(form);
				}
				addressChangeService.setAddress(address);
			}

		}
	}

}
